package com.zdsoft.finance.product.repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import com.zdsoft.finance.product.entity.ProductDocTemp;
import com.zdsoft.framework.core.common.domain.BaseEntity;
import com.zdsoft.framework.core.common.util.ObjectHelper;

/**
 * 产品模板设定操作仓库jpa实现
 * @author longwei
 * @date 2016/11/21
 * @version 1.0
 */
public class ProductDocTempRepositoryImpl {
	
	//hql查询头部
	private StringBuffer hqlBuffer = new StringBuffer("from ProductDocTemp where 1=1 ");
	
	@PersistenceContext
	private EntityManager em;
	
	/**
	 * 通过对象查询列表实现
	 * @param productDocTemp 查询对象
	 * @param pageable 分页信息
	 * @return 页面列表
	 */
	@SuppressWarnings("unchecked")
	public Page<ProductDocTemp> queryByCons(ProductDocTemp productDocTemp, Pageable pageable){
		//条件组装
		StringBuffer whereHqlBuffer = new StringBuffer(" and isDeleted=:isDeleted");
		if(ObjectHelper.isNotEmpty(productDocTemp.getName())){
			whereHqlBuffer.append(" and name like :name ");
		}
		if(ObjectHelper.isNotEmpty(productDocTemp.getStatus())){
			whereHqlBuffer.append(" and status = :status");
		}
		
		if(ObjectHelper.isNotEmpty(productDocTemp.getProductDocType().getId())){
			whereHqlBuffer.append(" and productDocType.id = :docTypeId");
		}
		whereHqlBuffer.append(" order by createTime desc");
		
		//参数组装
		Query query = em.createQuery(this.hqlBuffer.toString() + whereHqlBuffer.toString());
		Query countQ = em.createQuery("select count(*) " + this.hqlBuffer.toString() + whereHqlBuffer.toString());
		query.setParameter("isDeleted",!BaseEntity.DELETED);
		countQ.setParameter("isDeleted", !BaseEntity.DELETED);
		
		if(ObjectHelper.isNotEmpty(productDocTemp.getName())){
			query.setParameter("name","%"+productDocTemp.getName()+"%");
			countQ.setParameter("name","%"+ productDocTemp.getName()+"%");
		}
		if(ObjectHelper.isNotEmpty(productDocTemp.getStatus())){
			query.setParameter("status",productDocTemp.getStatus());
			countQ.setParameter("status", productDocTemp.getStatus());
		}
		if(ObjectHelper.isNotEmpty(productDocTemp.getProductDocType().getId())){
			query.setParameter("docTypeId",productDocTemp.getProductDocType().getId());
			countQ.setParameter("docTypeId", productDocTemp.getProductDocType().getId());
		}
		
		//查询
		query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
		query.setMaxResults(pageable.getPageSize());
		Page<ProductDocTemp> pager = new PageImpl<>(query.getResultList(),pageable,(Long)countQ.getSingleResult());
		return pager;
	}
}
